// 导入父类（注意：这里需要明确导入父类，而非仅引入文件）
import BaseBarChartComponent from "./base-bar-chart.js";

class StackedBarChart extends BaseBarChartComponent {
    // 重写观察的属性列表，添加数据文件路径
    static get observedAttributes() {
        const parentAttributes = super.observedAttributes;
        return [
            ...parentAttributes,
            'series-show-legend_radio',       // 是否显示图例
            'series-show-markline_radio',     // 是否显示标线
            'series-bar-width_number',        // 柱形宽度
            'base-data-url_text'                 // 数据文件路径
        ];
    }

    constructor() {
        super();
        this.data = null;       // 存储加载的数据
        this.loading = false;   // 数据加载状态
        // 预设一组颜色用于不同系列
        this.colors = [
            '#5470c6', '#91cc75', '#fac858', '#ee6666',
            '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'
        ];
    }

    // 重写默认配置
    getDefaultConfig() {
        const parentConfig = super.getDefaultConfig();

        // 配置图例
        parentConfig.legendAttrs = [
            ['legend-show_radio', true],
            ['legend-top_slider', 'top'],
            ['legend-left_slider', 'center'],
            ['legend-orient_select', 'horizontal']
        ];

        // X轴配置 - 数据将从加载的JSON中动态获取
        parentConfig.xAxisAttrs = [
            ['xaxis-type_text', 'category'],
            ['xaxis-data_array', '[]'],
            ['xaxis-axisline-show_radio', true]
        ];

        // Y轴配置
        parentConfig.yAxisAttrs = [
            ['yaxis-type_text', 'value'],
            ['yaxis-axisline-show_radio', true],
            ['yaxis-splitline-show_radio', true]
        ];

        // 系列配置
        parentConfig.seriesAttrs = [
            ['series-show-legend_radio', true],
            ['series-show-markline_radio', false],
            ['series-bar-width_number', 20],
            ['base-data-url_text', '']       // 数据文件路径
        ];

        return parentConfig;
    }

    // 从文件加载数据
    async loadDataFromFile(url) {
        if (!url) return null;

        try {
            this.loading = true;
            const response = await fetch(url);
            if (!response.ok) {
                throw new Error(`Failed to load data: ${response.statusText}`);
            }
            const data = await response.json();
            this.data = data;
            return data;
        } catch (error) {
            console.error('Error loading data:', error);
            // 加载失败时使用默认数据
            return this.getDefaultData();
        } finally {
            this.loading = false;
        }
    }

    // 提取所有类别名称（x轴数据）
    getCategoryNames(data) {
        if (!data || data.length === 0) return [];

        // 从第一个系列中提取所有名称
        const firstSeries = data[0];
        const firstSeriesKey = Object.keys(firstSeries)[0];
        return firstSeries[firstSeriesKey].map(item => item.name);
    }

    generateSeries(dataDemo, seriesConfig) {
        if (!dataDemo || dataDemo.length === 0) {
            return [];
        }

        const showMarkline = seriesConfig.showMarkline !== false;
        const barWidth = seriesConfig.barWidth || 20;
        // 左右堆叠分组配置，默认平均分组，可通过seriesConfig自定义
        const stackGroups = seriesConfig.stackGroups || this.getDefaultStackGroups(dataDemo.length);

        // 动态生成系列配置
        return dataDemo.map((seriesItem, seriesIndex) => {
            const seriesName = Object.keys(seriesItem)[0];
            const seriesData = seriesItem[seriesName];

            // 为每个系列分配不同的颜色
            const colorIndex = seriesIndex % this.colors.length;
            const seriesColor = this.colors[colorIndex];

            // 根据分组决定堆叠方向（左侧/右侧）
            const stackGroup = stackGroups[seriesIndex] || 'left';
            const stackId = stackGroup === 'right' ? 'stack-right' : 'stack-left';

            return {
                name: seriesName,
                type: 'bar',
                stack: stackId,  // 按左右分组使用不同的堆叠ID
                barWidth: barWidth,
                emphasis: {
                    focus: 'series'
                },
                itemStyle: {
                    color: seriesColor
                },
                // 为每个堆叠组添加标线
                markLine: showMarkline ? {
                    lineStyle: {
                        type: 'dashed',
                        color: seriesColor
                    },
                    data: [[{ type: 'min' }, { type: 'max' }]]
                } : undefined,
                // 提取数据值
                data: seriesData.map(item => item.value),

            };
        });
    }

// 辅助方法：默认分组（前半左堆叠，后半右堆叠）
    getDefaultStackGroups(seriesCount) {
        const midIndex = Math.ceil(seriesCount / 2);
        return Array.from({ length: seriesCount }, (_, i) =>
            i < midIndex ? 'left' : 'right'
        );
    }

    // 重写默认数据，匹配新的JSON格式
    getDefaultData() {
        return [
            {
                "销售": [
                    {"name":"衬衫","value":2},
                    {"name":"羊毛衫","value":1},
                    {"name":"雪纺衫","value":3},
                    {"name":"裤子","value":2},
                    {"name":"高跟鞋","value":4},
                    {"name":"袜子","value":4}
                ]
            },
            {
                "销售1": [
                    {"name":"衬衫","value":5},
                    {"name":"羊毛衫","value":4},
                    {"name":"雪纺衫","value":4},
                    {"name":"裤子","value":2},
                    {"name":"高跟鞋","value":5},
                    {"name":"袜子","value":4}
                ]
            },
            {
                "销售2": [
                    {"name":"衬衫","value":3},
                    {"name":"羊毛衫","value":4},
                    {"name":"雪纺衫","value":6},
                    {"name":"裤子","value":7},
                    {"name":"高跟鞋","value":8},
                    {"name":"袜子","value":4}
                ]
            }
        ];
    }

    // 重写渲染方法
    renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig, data = null) {

        // 加载数据（从文件或使用默认数据）
        const dataDemo = data || this.getDefaultData();

        // 从数据中提取类别名称作为X轴数据
        const categoryNames = this.getCategoryNames(dataDemo);
        xAxisConfig.data = categoryNames;

        // 配置提示框
        const tooltipConfig = {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        };

        // 控制图例显示
        if (seriesConfig.showLegend === false) {
            legendConfig.show = false;
        }

        // 调用父类方法完成渲染
        super.renderChart(
            { ...seriesConfig, tooltip: tooltipConfig },
            titleConfig,
            gridConfig,
            xAxisConfig,
            yAxisConfig,
            legendConfig,
            dataDemo
        );
    }

    // 处理属性变化
    handleAttributeChange(name, value, currentOptions) {
        super.handleAttributeChange(name, value, currentOptions);

    }

    // 重新渲染图表
    reRenderChart() {
        const { buildConfig } = window.attributeUtils;
        const config = this.getDefaultConfig();

        const seriesConfig = buildConfig(this, config.seriesAttrs);
        const titleConfig = buildConfig(this, config.titleAttrs);
        const gridConfig = buildConfig(this, config.gridAttrs);
        const xAxisConfig = buildConfig(this, config.xAxisAttrs);
        const yAxisConfig = buildConfig(this, config.yAxisAttrs);
        const legendConfig = buildConfig(this, config.legendAttrs);

        this.renderChart(seriesConfig, titleConfig, gridConfig, xAxisConfig, yAxisConfig, legendConfig);
    }

    // 当组件连接到DOM时渲染图表
    connectedCallback() {
        super.connectedCallback();
        this.reRenderChart();
    }
}

// 注册自定义元素
customElements.define('stacked-column-bar-chart', StackedBarChart);
